/**
 * 主应用程序逻辑
 * 负责前端交互、数据处理、文件上传等核心功能
 */

class DataConversionApp {
    constructor() {
        this.currentStep = 1;
        this.maxSteps = 5;
        this.uploadedFile = null;
        this.sourceData = null;
        this.convertedData = null;
        this.conversionConfig = null;
        
        this.init();
    }

    /**
     * 初始化应用程序
     */
    init() {
        this.bindEvents();
        this.initFileUpload();
        this.updateStepDisplay();
        this.loadConversionTypes();
    }

    /**
     * 绑定事件监听器
     */
    bindEvents() {
        // 步骤导航
        document.getElementById('nextStep1').addEventListener('click', () => this.nextStep());
        document.getElementById('nextStep2').addEventListener('click', () => this.nextStep());
        document.getElementById('nextStep3').addEventListener('click', () => this.nextStep());
        document.getElementById('nextStep4').addEventListener('click', () => this.nextStep());
        
        document.getElementById('prevStep2').addEventListener('click', () => this.prevStep());
        document.getElementById('prevStep3').addEventListener('click', () => this.prevStep());
        document.getElementById('prevStep4').addEventListener('click', () => this.prevStep());
        document.getElementById('prevStep5').addEventListener('click', () => this.prevStep());

        // 转换类型选择
        document.getElementById('conversionType').addEventListener('change', this.handleConversionTypeChange.bind(this));
        
        // 文件上传
        document.getElementById('uploadBtn').addEventListener('click', this.handleFileUpload.bind(this));
        
        // 数据转换
        document.getElementById('startConversion').addEventListener('click', this.startConversion.bind(this));
        
        // 重置流程
        document.getElementById('resetProcess').addEventListener('click', this.resetProcess.bind(this));
    }

    /**
     * 初始化文件上传功能
     */
    initFileUpload() {
        const fileInput = document.getElementById('fileInput');
        const uploadArea = document.getElementById('file-upload-area');
        
        // 文件选择
        fileInput.addEventListener('change', this.handleFileSelect.bind(this));
        
        // 拖拽上传
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                this.processFile(files[0]);
            }
        });
    }

    /**
     * 加载转换类型选项
     */
    loadConversionTypes() {
        const select = document.getElementById('conversionType');
        const types = configManager.get('conversionTypes');
        
        select.innerHTML = '<option value="">请选择转换类型</option>';
        
        for (const [key, config] of Object.entries(types)) {
            const option = document.createElement('option');
            option.value = key;
            option.textContent = config.name;
            option.title = config.description;
            select.appendChild(option);
        }
    }

    /**
     * 处理转换类型变化
     */
    handleConversionTypeChange(event) {
        const type = event.target.value;
        if (type) {
            this.conversionConfig = configManager.getConversionConfig(type);
            this.updateBusinessRules(type);
        }
    }

    /**
     * 处理文件选择
     */
    handleFileSelect(event) {
        const file = event.target.files[0];
        if (file) {
            this.processFile(file);
        }
    }

    /**
     * 处理文件
     */
    processFile(file) {
        // 验证文件类型和大小
        if (!this.validateFile(file)) {
            return;
        }
        
        this.uploadedFile = file;
        this.displayFileInfo(file);
        
        // 预览文件内容
        this.previewFileContent(file);
        
        // 启用上传按钮
        document.getElementById('uploadBtn').disabled = false;
    }

    /**
     * 验证文件
     */
    validateFile(file) {
        const maxSize = configManager.get('upload.maxFileSize');
        const allowedTypes = configManager.get('upload.allowedTypes');
        
        if (file.size > maxSize) {
            this.showToast('error', configManager.getErrorMessage('FILE_TOO_LARGE'));
            return false;
        }
        
        const extension = '.' + file.name.split('.').pop().toLowerCase();
        if (!allowedTypes.includes(extension)) {
            this.showToast('error', configManager.getErrorMessage('INVALID_FILE_TYPE'));
            return false;
        }
        
        return true;
    }

    /**
     * 显示文件信息
     */
    displayFileInfo(file) {
        document.getElementById('file-name').textContent = file.name;
        document.getElementById('file-size').textContent = this.formatFileSize(file.size);
        document.getElementById('file-info').classList.remove('d-none');
    }

    /**
     * 预览文件内容
     */
    async previewFileContent(file) {
        try {
            this.showLoading(true);
            
            if (file.name.endsWith('.csv')) {
                await this.previewCSV(file);
            } else {
                await this.previewExcel(file);
            }
            
            this.showLoading(false);
        } catch (error) {
            this.showLoading(false);
            this.showToast('error', '文件预览失败: ' + error.message);
        }
    }

    /**
     * 预览Excel文件
     */
    async previewExcel(file) {
        const data = await this.readFileAsArrayBuffer(file);
        const workbook = XLSX.read(data, { type: 'array' });
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
        
        this.sourceData = jsonData;
        this.renderDataPreview(jsonData);
    }

    /**
     * 预览CSV文件
     */
    async previewCSV(file) {
        const text = await this.readFileAsText(file);
        const lines = text.split('\n').filter(line => line.trim());
        const data = lines.map(line => line.split(','));
        
        this.sourceData = data;
        this.renderDataPreview(data);
    }

    /**
     * 渲染数据预览
     */
    renderDataPreview(data) {
        if (!data || data.length === 0) {
            document.getElementById('data-preview').innerHTML = 
                '<div class="text-center text-muted p-4">无有效数据</div>';
            return;
        }

        const maxRows = 50; // 限制预览行数
        const previewData = data.slice(0, maxRows);
        
        let html = '<table class="table table-striped table-hover">';
        
        // 表头
        if (previewData.length > 0) {
            html += '<thead><tr>';
            for (let i = 0; i < previewData[0].length; i++) {
                html += `<th>列${i + 1}</th>`;
            }
            html += '</tr></thead>';
        }
        
        // 数据行
        html += '<tbody>';
        previewData.forEach((row, index) => {
            html += '<tr>';
            row.forEach(cell => {
                html += `<td>${this.escapeHtml(cell || '')}</td>`;
            });
            html += '</tr>';
        });
        html += '</tbody></table>';
        
        document.getElementById('data-preview').innerHTML = html;
        
        // 更新统计信息
        document.getElementById('total-rows').textContent = data.length;
        document.getElementById('total-columns').textContent = data[0]?.length || 0;
        document.getElementById('file-size-display').textContent = this.formatFileSize(this.uploadedFile.size);
    }

    /**
     * 步骤控制
     */
    nextStep() {
        if (this.currentStep < this.maxSteps) {
            this.currentStep++;
            this.updateStepDisplay();
        }
    }

    prevStep() {
        if (this.currentStep > 1) {
            this.currentStep--;
            this.updateStepDisplay();
        }
    }

    /**
     * 更新步骤显示
     */
    updateStepDisplay() {
        // 更新步骤指示器
        document.querySelectorAll('.step').forEach((step, index) => {
            const stepNum = index + 1;
            step.classList.remove('active', 'completed');
            
            if (stepNum === this.currentStep) {
                step.classList.add('active');
            } else if (stepNum < this.currentStep) {
                step.classList.add('completed');
            }
        });

        // 显示对应的面板
        document.querySelectorAll('.step-panel').forEach((panel, index) => {
            panel.classList.remove('active');
            if (index + 1 === this.currentStep) {
                panel.classList.add('active');
            }
        });
    }

    /**
     * 工具方法
     */
    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    readFileAsArrayBuffer(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = e => resolve(e.target.result);
            reader.onerror = reject;
            reader.readAsArrayBuffer(file);
        });
    }

    readFileAsText(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = e => resolve(e.target.result);
            reader.onerror = reject;
            reader.readAsText(file, 'utf-8');
        });
    }

    showLoading(show) {
        const overlay = document.getElementById('loading-overlay');
        if (show) {
            overlay.classList.remove('d-none');
        } else {
            overlay.classList.add('d-none');
        }
    }

    showToast(type, message) {
        const container = document.getElementById('toast-container');
        const toastId = 'toast-' + Date.now();
        
        const toastHtml = `
            <div id="${toastId}" class="toast align-items-center text-white bg-${type === 'error' ? 'danger' : 'success'} border-0" role="alert">
                <div class="d-flex">
                    <div class="toast-body">${message}</div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            </div>
        `;
        
        container.insertAdjacentHTML('beforeend', toastHtml);
        const toast = new bootstrap.Toast(document.getElementById(toastId));
        toast.show();
        
        // 自动移除
        setTimeout(() => {
            const element = document.getElementById(toastId);
            if (element) element.remove();
        }, 5000);
    }
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', function() {
    window.app = new DataConversionApp();
});